package com.infindo.frame.data.net;


import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import com.infindo.frame.data.DataHandler;
import com.infindo.frame.data.DataProcessor;
import com.infindo.frame.data.ImageCache;
import com.infindo.frame.util.FileUtil;
import com.infindo.frame.util.StringUtil;
import com.tiantian.app.manager.Const;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

 
 
@SuppressWarnings("unused")
public class ImageGet extends DataHandler
{
	private Context context;
	private String imageUrl;
	private String type;
	private boolean isTransLocation;
	private int tryLotionTimes;
    private DataProcessor dataProc;
    private int position;

	public ImageGet(Context context,String url,int position,String type,DataProcessor dataProc,int dataHandlerNo,CallbackListener listener) {
		super(dataHandlerNo,listener);
		this.setBolNeedTimer(true);
		this.context = context;
		this.dataProc = dataProc;
		this.imageUrl = url;
		this.type = type;
		isTransLocation = false;
		tryLotionTimes = 0;
		this.position = position;
	}
	
	
	public void transLocation()
	{
		new Thread(this).start();
	}
	
	  protected byte[] processRequest(String imageUrl) {
		    byte[] bitmap = null;

		    FileInputStream inputStream = null;
		    String imageKey = ImageCache.getCacheKeyForUrl(imageUrl);
		    File cacheFile = new File(ImageCache.getCacheDirectory(context), imageKey);
		    if(cacheFile.exists()) {
		      try {
		        Date now = new Date();
		        long fileAgeInMs = now.getTime() - cacheFile.lastModified();
		        if(fileAgeInMs > ImageCache.getCacheRecheckAgeInMs()) {
		        	cacheFile.delete();
		        	
		        	return null;
		        }
		        inputStream = new FileInputStream(cacheFile);
		        bitmap  = FileUtil.getBytesFromIS(inputStream);//BitmapFactory.decodeFileDescriptor(inputStream.getFD(), null, null);
		        if(bitmap == null) {
		          throw new Exception("Could not create bitmap from image " + imageUrl.toString());
		        }
		      }
		      catch(Exception e) {
		    	  System.out.println("e:"+e.getMessage());
		      }
		      finally {
		        if(inputStream != null) {
		          try {
		            inputStream.close();
		          }
		          catch(IOException e) {
		        	  System.out.println("ioe:"+e.getMessage());
		          }
		        }
		      }
		    }

		    return bitmap;
		  }
	
	public void run() {
		Object result = null;
		try {
			result = processRequest(imageUrl);
			if(result ==null)
				result = get(URLEncoder.encode(imageUrl,"UTF-8"));
 
		} catch (Throwable e) {
			result = e;
		}
 
		if(isTransLocation && tryLotionTimes <3)
		{
			isTransLocation = false;
			transLocation();
			return;
		}
 		if(dataProc.checkNoCancelQueue(this.getDataHandlerNo()))
			this.getCallbackListener().callback(type,position,result);
		
	}
	
	public byte[] get(String url) {
 
		InputStream in = null;
		ByteArrayOutputStream bos = null;
		byte[] buffer = null;
		try {
			HttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams,
					Const.CONNECT_HTTP_TIMEOUT);
			HttpConnectionParams.setSoTimeout(httpParams,
					Const.CONNECT_SOCKET_TIMEOUT);
			
			hc = new DefaultHttpClient(httpParams);
			Log.i("imageUrl", "imageUrl:" +url);
			String userAgent = "Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10";

			HttpGet httpGet = new HttpGet(url);
			httpGet.addHeader("UserAgent",userAgent);
			
			startConnect();
			dataProc.getDataTimer().addConnect(this);
			
			HttpResponse response = hc.execute(httpGet);
			HttpEntity entity = response.getEntity();
			
			int code = response.getStatusLine().getStatusCode();
			Log.i("imageUrl","code:"+code);
			if (entity != null) {
				InputStream is = entity.getContent();
				//
			    String imageKey = ImageCache.getCacheKeyForUrl(url);
			    File cacheFile = new File(ImageCache.getCacheDirectory(context), imageKey);
			    if(!cacheFile.exists()) {
			    	cacheFile.createNewFile();
			    } 
			   	int BUFFER = 4096; 
			   	BufferedOutputStream dest = null;
				int count;
				byte data[] = new byte[BUFFER];
				
				FileOutputStream fos = new FileOutputStream(cacheFile);
				dest = new BufferedOutputStream(fos, BUFFER);
				while ((count = is.read(data, 0, BUFFER)) != -1) {
					dest.write(data, 0, count);
				}
				dest.flush();
				dest.close();
 
				//
//				buffer = FileUtil.getBytesFromIS(is);
				FileInputStream inputStream = new FileInputStream(cacheFile);
				buffer  = FileUtil.getBytesFromIS(inputStream);
				is.close();
				entity.consumeContent();

			}
			hc.getConnectionManager().shutdown();
            return buffer;
		}
		catch(SecurityException se){
			System.out.println("se:"+se.getMessage());
		}catch(InterruptedIOException ie){
			System.out.println("iro:"+ie.getMessage());
		}
		catch (IOException e) {
			System.out.println("ioe:"+e.getMessage());
		}catch(NullPointerException ne) {
			
		}finally {
			try {
				if (in != null)
					in.close();
				if (bos != null)
					bos.close();
				this.stopConnect();
			} catch (IOException ignored) {
				this.stopConnect();
			}
		}
		return null;
	}

    /**
     * Method description
     *
     */
	private byte[] addCapacity(byte rece[])
	{
		byte temp[]=new byte[rece.length+1024];
//		System.arraycopy(rece,0,temp,0,rece.length);
		return temp;
	}
	

	
}
